﻿//bibaoke.com

using Less.WebBrowserQuery.SelectorParamParser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Less.WebBrowserQuery
{
    /// <summary>
    /// HtmlDocument 扩展方法
    /// </summary>
    public static class HtmlDocumentExtensions
    {
        /// <summary>
        /// 使用 css 选择器查询元素
        /// </summary>
        /// <param name="document"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static HtmlElement[] Query(this HtmlDocument document, string param)
        {
            if (param.IsNull())
            {
                throw new ArgumentNullException("param");
            }

            ElementFilter[] filters = ParamParser.Parse(param);

            List<HtmlElement> list = document.All.Cast<HtmlElement>().ToList();

            return filters.SelectMany(i => i.Eval(document)).Distinct().OrderBy(i => list.IndexOf(i)).ToArray();
        }
    }
}
